//定制请求的实例

//导入axios  npm install axios
import axios from 'axios';
//定义一个变量,记录公共的前缀  ,  baseURL
const baseURL = '/api';
import { ElMessage } from 'element-plus';
import router from '@/router'
import { useTokenStore } from '@/store/token';
// 创建请求内容
const instance = axios.create({ baseURL })

// 添加请求拦截器
instance.interceptors.request.use(
    (config) => {
        const tokenStore = useTokenStore();
        if (tokenStore.token) {
            config.headers.Authorization = tokenStore.token
        }
        return config;
    },
    err => {
        ElMessage.error("服务异常")
        Promise.reject(err)
    }
)



//添加响应拦截器 拦截响应的数据内容
instance.interceptors.response.use(
    result => {
        if (result.data.code == 0) {
            return result.data;
        } else {
            ElMessage.error(result.data.msg ? result.data.msg : "出现错误")
            return Promise.reject(result.data)
        }
    },
    err => {
        if(err.response.status == 401){
            ElMessage.error("请先登录")
            router.push("/login")
        }else {
            ElMessage.error("服务异常")
        }

        return Promise.reject(err);//异步的状态转化成失败的状态
    }
)

export default instance;